<?php
declare (strict_types = 1);
// +----------------------------------------------------------------------
// | 课程订单
// +----------------------------------------------------------------------

namespace app\course\controller;

use app\BaseController;
use app\course\model\Course;
use app\course\model\CourseOrder;

class CourseOrderController extends BaseController
{
    /**
     * @OA\Get(path="/course_order",tags={"课程订单"},summary="列表",
     *   @OA\Parameter(name="authorization", in="header", description="Bearer token", @OA\Schema(type="string")),
     *   @OA\Parameter(name="page", in="query", description="页码", @OA\Schema(type="int", default="1")),
     *   @OA\Parameter(name="limit", in="query", description="行数", @OA\Schema(type="int", default="10")),
     *   @OA\Parameter(name="name", in="query", description="名称", @OA\Schema(type="string")),
     *   @OA\Parameter(name="order_sn", in="query", description="订单号", @OA\Schema(type="string")),
     *   @OA\Parameter(name="status", in="query", description="状态", @OA\Schema(type="int")),
     *   @OA\Response(response="200", description="successful operation")
     * )
     */
    public function index()
    {
        $param = $this->request->param();
        $where = [];
        if (!empty($param['id'])) {
            $where[] = ['id', '=', $param['id']];
        }
        if (!empty($param['title'])) {
            $where[] = ['title', 'like', '%' . $param['title'] . '%'];
        }
        if (!empty($param['category_id'])) {
            $where[] = ['category_id', '=', $param['category_id']];
        }
        $list = Course::with(['category' => function ($query) {
            $query->field('id,name');
        }])->where($where)->order('id desc')->paginate(10);
        $data = [
            'code' => 0,
            'message' => '正在请求中...',
            'count' => $list->total(),
            'data' => $list->items()
        ];
        return json($data);
    }

    public function save()
    {
        $param  = $this->request->param();
        $course = Course::find($param['course_id']);
        if (!$course) {
            $this->error('无数据');
        }
        $param['user_id'] = $this->user_id;

        $order = CourseOrder::where('user_id', $param['user_id'])
            ->where('course_id', $param['course_id'])
            ->find();
        if ($order) {
            $this->error('请勿重复下单');
        }
        $lesson = CourseOrder::create($param);
        if (!$lesson) {
            $this->error('操作失败');
        }
        $this->success('操作成功', $lesson);
    }

    public function read($id)
    {

    }

    public function update($id)
    {

    }

    public function delete($id)
    {

    }

    public function course_orders()
    {
        $list = CourseOrder::with(['course' => function ($query) {
            $query->field('id,title,thumb');
        }])->where('user_id', $this->user_id)->order('id desc')->paginate(10);
        $this->success('Success', $list);
    }
}